package com.atzongmaotan.reggie.service.impl;

import com.atzongmaotan.reggie.common.CustomeException;
import com.atzongmaotan.reggie.dto.SetmealDto;
import com.atzongmaotan.reggie.entity.Setmeal;
import com.atzongmaotan.reggie.entity.SetmealDish;
import com.atzongmaotan.reggie.mapper.SetmealMapper;
import com.atzongmaotan.reggie.service.SetmealDishService;
import com.atzongmaotan.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName:    SetmealServiceImpl
 * Package:  com.atzongmaotan.service.impl
 * Description:
 *
 * @Author: interface
 * @Create: 2024/6/14 - 上午5:52
 * @Version: v1.0
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    @Transactional
    public void saveSetmealAndSetmealDish(SetmealDto setmealDto) {
        //保存setmeal
        this.save(setmealDto);
        //保存setmealDish
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList = setmealDishList.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishList);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> idList) {
        //确定套餐是否为停售
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<Setmeal>();
        // in (1,2,3,4)
        queryWrapper.in(Setmeal::getId, idList);
        // status = 1
        queryWrapper.eq(Setmeal::getStatus, 1);
        int setmealCount = this.count(queryWrapper);
        if (setmealCount > 0) {
            throw new CustomeException("套餐正在售卖中,不能删除");
        }
        //删除套餐 id in ()va
        this.removeByIds(idList);

        //删除关系表中数据 setmeal_id in ()
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,idList);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
